package com.wuuxiang.i5xforyou.web;

import java.net.URI;
import java.util.HashMap;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import springfox.documentation.annotations.ApiIgnore;

@RestController
@RequestMapping("/api-docs")
public class ProxiedSwaggerController {

	@Autowired
	private LoadBalancerClient loadBalancerClient;

	private RestTemplate restTemplate;
	
	@PostConstruct
    void init() {
        this.restTemplate = new RestTemplate();
    }

	@ApiIgnore
	@GetMapping(value = "{serviceId}", produces = { "application/json", "application/hal+json" })
	public ResponseEntity<HashMap<String, Object>> processSwaggerRequest(@PathVariable("serviceId") String serviceId, String contextpath, 
			HttpServletRequest request) {
		ServiceInstance selectedInstance = loadBalancerClient.choose(serviceId);
		if (selectedInstance != null) {
			URI serviceURI = selectedInstance.getUri();
			String documentationUri = serviceURI.toString() + contextpath + "/v2/api-docs";
			try {
				ResponseEntity<HashMap<String, Object>> swaggerResponse = restTemplate.exchange(documentationUri, HttpMethod.GET, null, new ParameterizedTypeReference<HashMap<String, Object>>() {});
				HashMap<String, Object> swagger = swaggerResponse.getBody();
				swagger.put("basePath", serviceURI.toString() + contextpath);
				return new ResponseEntity<>(swagger, HttpStatus.OK);
			} catch (Exception e) {
				return new ResponseEntity<>(HttpStatus.NOT_FOUND);
			}
		} else {
			return new ResponseEntity<>(HttpStatus.NOT_FOUND);
		}
	}

}
